package com.azkj.album.view.base;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.Window;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.azkj.album.MyApplication;
import com.azkj.album.R;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.Constants;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.callback.ServiceCallback;
import com.azkj.album.network.networkframe.net.exception.ApiException;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.utils.ImageUtils;
import com.azkj.album.utils.SaveImgToLocalTool;
import com.azkj.album.utils.ShareUtils;
import com.azkj.album.utils.StatusBarUtil;
import com.azkj.album.utils.Utils;
import com.azkj.album.view.activity.HomeActivity;
import com.azkj.album.view.activity.LoginActivity;
import com.bytedance.sdk.open.aweme.base.ImageObject;
import com.bytedance.sdk.open.aweme.base.MediaContent;
import com.bytedance.sdk.open.aweme.share.Share;
import com.bytedance.sdk.open.douyin.DouYinOpenApiFactory;
import com.bytedance.sdk.open.douyin.api.DouYinOpenApi;
import com.gyf.barlibrary.FlymeOSStatusBarFontUtils;
import com.gyf.barlibrary.OSUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;


public abstract class BaseActivity extends AppCompatActivity {

    protected final String TAG = this.getClass().getSimpleName();
    protected SharedPreferences mSharedPreferences;
    // IWXAPI 是第三方app和微信通信的openapi接口
    protected IWXAPI iwxapi;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    startActivity(new Intent(BaseActivity.this, LoginActivity.class));
                    finish();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBarTVColor();
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mSharedPreferences =
                MyApplication.getApplication().getSharedPreferences(Constants.SP_NAME, Context.MODE_PRIVATE);
        iwxapi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);

        StatusBarUtil.immersive(this);
        initView();
        initPresenter();
        initData();


    }

    // 字体大小不跟随系统
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(getConfigurationContext(newBase));
    }

    private static Context getConfigurationContext(Context context) {
        Configuration configuration = context.getResources().getConfiguration();
        configuration.fontScale = 1;
        return context.createConfigurationContext(configuration);
    }

    /**
     * 初始化数据
     */
    public abstract void initView();

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 初始化presenter 和 adapter
     */
    protected abstract void initPresenter();


    protected abstract int getLayoutId();

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case MessageType.TYPE_START_LOGIN_ACTIVITY:
                if (!(this instanceof LoginActivity)) {
                    handler.sendEmptyMessageDelayed(0, 0);
                }
                break;
            case MessageType.TYPE_START_HOME_ACTIVITY:
                if (!(this instanceof HomeActivity)) finish();
                break;
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 初始化状态栏和导航栏
     */
    private void initBarTVColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;  //防止系统栏隐藏时内容区域大小发生变化
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !OSUtils.isEMUI3_1())
                uiFlags = setStatusBarDarkFont(uiFlags); //android 6.0以上设置状态栏字体为暗色
            getWindow().getDecorView().setSystemUiVisibility(uiFlags);
        }
        if (OSUtils.isMIUI6Later())
            setMIUIStatusBarDarkFont(getWindow(), true);         //修改miui状态栏字体颜色
        if (OSUtils.isFlymeOS4Later()) {          // 修改Flyme OS状态栏字体颜色
            FlymeOSStatusBarFontUtils.setStatusBarDarkIcon(getWindow(), true);
        }
    }

    /**
     * Sets status bar dark font.
     * 设置状态栏字体颜色，android6.0以上
     */
    private int setStatusBarDarkFont(int uiFlags) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return uiFlags | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        } else {
            return uiFlags;
        }
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @return boolean 成功执行返回true
     */
    private void setMIUIStatusBarDarkFont(Window window, boolean darkFont) {
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (darkFont) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mSharedPreferences.getBoolean("isCheckedProtocol", false)) {
            MobclickAgent.onResume(this);
            MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
            MobclickAgent.setDebugMode(true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mSharedPreferences.getBoolean("isCheckedProtocol", false)) {
            MobclickAgent.onPause(this);
        }
    }

    protected boolean isWxExited() {
        final PackageManager packageManager = getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    protected boolean isDyExited() {
        final PackageManager packageManager = getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.ss.android.ugc.aweme.lite") || pn.equals("com.ss.android.ugc.aweme")) {
                    return true;
                }
            }
        }
        return false;
    }

    public void shareImageToWxMore(ArrayList<Pair<String, String>> imageUrlsAndName){
        showLoading();
        new Thread(()->{
            ArrayList<File> files = new ArrayList<>();
            for (Pair<String, String> pair : imageUrlsAndName) {
                File file = SaveImgToLocalTool.saveImageToSdCard(getApplicationContext(), pair.first, pair.second);
                if (file != null){
                    files.add(file);
                }
            }
            runOnUiThread(() -> {
                hideLoading();
                ShareUtils.shareWeChatByImgList(files);
            });
        }).start();
    }

    public void shareImageToWx(String mid, String imgUrl, boolean wx_friend, int position) {
        showLoading();
        ImageUtils.getImage(imgUrl, new ImageUtils.HttpCallBackListener() {
            @Override
            public void onFinish(Bitmap bitmap) {
                runOnUiThread(() -> {
                    hideLoading();
                    shareImageToWx(bitmap, wx_friend);
                });
                if (!TextUtils.isEmpty(mid)) {
                    //下载后增加使用次数
                    NetworkMaster.getInstance().getCommonService().getAddUseCount(mid, new ServiceCallback() {
                        @Override
                        public void onSuccess(Object jsonObj) {
                            EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_ACTIVITY_MAP_REFRESH, position));
                        }

                        @Override
                        public void onError(ApiException apiException) {
                            ToastUtils.showCenterToast(apiException.errorInfo.error);
                        }
                    });
                }
            }

            @Override
            public void onError() {
                runOnUiThread(() ->{
                    hideLoading();
                    ToastUtils.showCenterToast("分享失败");
                });
            }

            @Override
            public void onFinish(String path, int position) {

            }
        });
    }

    public void shareImageToWx(Bitmap bitmap, boolean wx_friend) {

        if (!isWxExited()) {
            ToastUtils.showCenterToast("安装微信后分享");
            return;
        }

        try {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float scale = (1024f * 8 * 400) / (width * height);
//            if (scale < 1) {
//                ToastUtils.showCenterToast("图片太大无法直接微信分享，请先保存图片到手机再分享");
//                return;
//            }
        } catch (Exception e) {
            ToastUtils.showCenterToast("图片太大无法直接微信分享，请先保存图片到手机再分享");
            return;
        }


        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg2 = new WXMediaMessage();
        msg2.mediaObject = imgObj;

        //设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 50, 50, true);
        msg2.thumbData = Utils.bitmapToBytes(thumbBmp);

        //构造一个Req
        SendMessageToWX.Req req2 = new SendMessageToWX.Req();
        req2.message = msg2;
        req2.scene = wx_friend ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        //调用api接口，发送数据到微信
        iwxapi.sendReq(req2);
        bitmap.recycle();
        thumbBmp.recycle();

    }

    public void shareWeb(String ThumbImageUrl, boolean isWxCircle, String shareUrl, String shareTiTle, String shareDesc) {
        if (!TextUtils.isEmpty(ThumbImageUrl)){
            ImageUtils.getImage(ThumbImageUrl, new ImageUtils.HttpCallBackListener() {
                @Override
                public void onFinish(Bitmap bitmap) {
                    runOnUiThread(() -> {
                        sendShareWxWeb(isWxCircle, shareUrl, shareTiTle, shareDesc, null, ImageUtils.bmpToByteArray(bitmap, 32));
                    });
                }

                @Override
                public void onFinish(String path, int position) {

                }

                @Override
                public void onError() {

                }
            });
        }else {
            shareWeb(isWxCircle, shareUrl, shareTiTle, shareDesc);
        }
    }

    public void shareWeb(boolean isWxCircle, String shareUrl, String shareTiTle, String shareDesc) {
        if (!isWxExited()) {
            ToastUtils.showNormalShortToast("安装微信后分享");
            return;
        }
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_logo_small, null);
        sendShareWxWeb(isWxCircle, shareUrl, shareTiTle, shareDesc, bitmap, null);
    }

    private void sendShareWxWeb(boolean isWxCircle, String shareUrl, String shareTiTle, String shareDesc, Bitmap bitmap, byte[] bitmapByte){
        //初始化一个WXWebpageObject，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = shareUrl;

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg3 = new WXMediaMessage(webpage);
        msg3.title = TextUtils.isEmpty(shareTiTle) ? "冻品图册" : shareTiTle;
        msg3.description = shareDesc;
        if (bitmap == null){
            msg3.thumbData = bitmapByte;
        }else {
            msg3.setThumbImage(bitmap);
        }

        //构造一个Req
        SendMessageToWX.Req req3 = new SendMessageToWX.Req();
//                req.transaction = buildTransaction("webpage");
        req3.message = msg3;
        req3.scene = isWxCircle ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        //调用api接口，发送数据到微信
        iwxapi.sendReq(req3);
    }

    //多图分享
    public void shareImgToDyMore(ArrayList<Pair<String, String>> imageUrlsAndName){
        if (!isDyExited()) {
            ToastUtils.showCenterToast("安装抖音后分享");
            return;
        }
        showLoading();
        new Thread(()->{
            ArrayList<File> files = new ArrayList<>();
            for (Pair<String, String> pair : imageUrlsAndName) {
                File file = SaveImgToLocalTool.saveImageToSdCard(getApplicationContext(), pair.first, pair.second);
                if (file != null){
                    files.add(file);
                }
            }
            ArrayList<String> imageUris = new ArrayList<String>();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                for (File f : files) {
                    String imageContentUri = getFileUri(MyApplication.getApplication(), f.getAbsolutePath());
                    imageUris.add(imageContentUri);
                }
            } else {
                for (File f : files) {
                    imageUris.add(f.getAbsolutePath());
                }
            }
            runOnUiThread(() -> {
                hideLoading();
                shareImgToDy(imageUris);
            });
        }).start();


    }

    private void shareImgToDy(ArrayList<String> mUri){
        DouYinOpenApi douyinOpenApi = DouYinOpenApiFactory.create(BaseActivity.this);
        if (douyinOpenApi.isShareSupportFileProvider() &&
                android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
//            ArrayList<String> images = new ArrayList<>();
//            images.add(xxx);  // 将FileProvider格式的路径传的该list中
            Share.Request request = new Share.Request();
            ImageObject imageObject = new ImageObject();
            imageObject.mImagePaths = mUri;
            MediaContent mediaContent = new MediaContent();
            mediaContent.mMediaObject = imageObject;
            request.mMediaContent = mediaContent;
            douyinOpenApi.share(request);
        } else {
            Log.d(TAG, "shareImgToDy: ====  版本不符合");
        }
    }

    public String getFileUri(Context context, String filePath) {
        File file = new File(filePath);
        Uri contentUri = FileProvider.getUriForFile(context,
                "com.azkj.album.provider",file);
        context.grantUriPermission("com.ss.android.ugc.aweme",
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.grantUriPermission("com.ss.android.ugc.aweme.lite",
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return contentUri.toString();
    }


    public void shareImgToDy(String mid, String url, String fileName, int position) {

        if (!isDyExited()) {
            ToastUtils.showCenterToast("安装抖音后分享");
            return;
        }

        ImageUtils.downloadImgUrl(url, fileName, new ImageUtils.HttpCallBackListener() {
            @Override
            public void onFinish(Bitmap bitmap) {

            }

            @Override
            public void onFinish(String path, int position) {
                runOnUiThread(() -> {
                    ArrayList<String> mUri = new ArrayList<>();
                    mUri.add(getFileUri(BaseActivity.this, path));
                    shareImgToDy(mUri);
                    if(!TextUtils.isEmpty(mid)){
                        //下载后增加使用次数
                        NetworkMaster.getInstance().getCommonService().getAddUseCount(mid, new ServiceCallback() {
                            @Override
                            public void onSuccess(Object jsonObj) {
                                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_ACTIVITY_MAP_REFRESH, position));

                            }

                            @Override
                            public void onError(ApiException apiException) {
                                ToastUtils.showCenterToast(apiException.errorInfo.error);
                            }
                        });
                    }
                });

            }

            @Override
            public void onError() {
                runOnUiThread(() -> ToastUtils.showCenterToast("分享失败"));
            }
        });
    }

    private LoadingPopupView loadingPopupView;
    public void showLoading(String content){
        if (loadingPopupView == null){
            loadingPopupView = new XPopup.Builder(BaseActivity.this)
                    .dismissOnTouchOutside(false)
                    .asLoading(content);
        }
        if (loadingPopupView.isDismiss()){
            loadingPopupView.show();
        }
    }
    public void showLoading(){
        showLoading("正在分享...");
    }

    public void hideLoading(){
        if (loadingPopupView != null && loadingPopupView.isShow()){
            loadingPopupView.dismiss();
        }
    }


}